package com.nopay.cdxphone.ui.ativity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.cdxphone.baiduocr.OCRAPI;
import com.nopay.cdxphone.base.BaseActivity;
import com.nopay.cdxphone.bean.CommonResponse;
import com.nopay.cdxphone.bean.request.SaveCallTaskRequest;
import com.nopay.cdxphone.bean.response.SaveCallTaskResponse;
import com.nopay.cdxphone.custom_view.BottomPopupWindow;
import com.nopay.cdxphone.custom_view.BottomSheetDialog;
import com.nopay.cdxphone.dialog.DialogLoading;
import com.sl.utakephoto.compress.CompressConfig;
import com.sl.utakephoto.crop.CropOptions;
import com.sl.utakephoto.exception.TakeException;
import com.sl.utakephoto.manager.ITakePhotoResult;
import com.sl.utakephoto.manager.TakePhotoManager;
import com.sl.utakephoto.manager.UTakePhoto;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.nopay.cdxphone.CallGroupEnum;
import com.nopay.cdxphone.Constants;
import com.nopay.cdxphone.R;
import com.nopay.cdxphone.databinding.ActivityImportFileBinding;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ProjectName: myVisualPhone
 * @Package: cn.cn.myvisualphone.ui.ativity
 * @ClassName: ForgetActivity
 * @Description: java类作用描述
 * @Author: anqi
 * @CreateDate: 2021/5/23 8:05
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/5/23 8:05
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class FileImportActivity extends BaseActivity<ActivityImportFileBinding> {

    private int mPos;
    private ArrayList<String> typeList = new ArrayList<>();

    @Override
    protected void init(Bundle savedInstanceState, Object... preData) {
        binding.rlRoot.setPadding(0, getStatusBarHeight(FileImportActivity.this), 0, 0);
        binding.ivBack.setOnClickListener(v -> mSwipeBackHelper.backward());

        typeList.add("照片");
        typeList.add("微信");
        typeList.add("粘贴导入");
        typeList.add("电脑");
        binding.btnBeginImport.setOnClickListener(v -> {
            //照片、微信、电脑
            new BottomSheetDialog().initSimpleBottomsheet("导入方式",
                    false,
                    FileImportActivity.this,
                    typeList,
                    mPos,
                    new BottomSheetDialog.OnBottomSheetListener() {
                        @Override
                        public void onSelected(int position) {
                            switch (position) {
                                case 0: // 照片
                                    chooseImage();
                                    break;

                                case 1: // 微信
                                    requetPermission(1);
                                    break;

                                case 2: // 复制粘贴
                                    mSwipeBackHelper.forward(FileImportByClipBoardActivity.class);
                                    break;

                                case 3: // 电脑
                                    mSwipeBackHelper.forward(ComputerImportCourseActivity.class);
                                    break;
                            }
                        }

                        @Override
                        public void onCancel() {

                        }

                        @Override
                        public void onDismiss() {

                        }
                    }
            ).show();
        });

        binding.btnImportExample.setOnClickListener(v -> mSwipeBackHelper.forward(FileImportSampleActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                if (requestCode == Constants.REQ_OPEN_WECHAT) {
                    if(mDialogLoading == null) mDialogLoading = new DialogLoading(FileImportActivity.this);
                    mDialogLoading.show("微信导入中...");
                    String fileName = data.getStringExtra(Constants.WECHAT_FILE_NAME);
                    String encodeFileName = fileName;
                    try {
                        encodeFileName = URLEncoder.encode(fileName, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    File taskFile = new File(FileImportWechatActivity.FOLDER_WEIXIN + fileName);
                    Map<String, RequestBody> bodyMap = new HashMap<>();
                    RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), taskFile);
                    MultipartBody.Part.createFormData(fileName, encodeFileName, requestBody);
                    bodyMap.put("file\"; filename=\"" + encodeFileName, requestBody);
                    String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
                    api.doImportCallTaskToGroup(bodyMap, phone, CallGroupEnum.IMPORT_WECHART.getGroupId()).enqueue(new Callback<CommonResponse>() {
                        @Override
                        public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                            mDialogLoading.dismiss();
                            if (response.body() != null) {
                                if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                    ToastUtils.showShort("导入成功");

                                    Intent intent = new Intent();
                                    intent.putExtra(Constants.FILE_IMPORT_TASK_NAME, "微信导入名单");
                                    setResult(RESULT_OK, intent);
                                    mSwipeBackHelper.backward();
                                } else {
                                    String error = response.body().getMsg();
                                    error = error == null ? "" : error;
                                    error = error.length() > 100 ? error.substring(0, 100) : error;
                                    ToastUtils.showShort(error);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<CommonResponse> call, Throwable t) {
                            mDialogLoading.dismiss();
                            ToastUtils.showShort(FileImportActivity.this.getResources().getString(R.string.call_api_error));
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    private void requetPermission(int request) {
        if (ContextCompat.checkSelfPermission(FileImportActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(FileImportActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, request);
        }else{
            mSwipeBackHelper.forward(FileImportWechatActivity.class, Constants.REQ_OPEN_WECHAT);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {//选择了“始终允许”
                    ToastUtils.showShort("" + "权限" + permissions[i] + "申请成功");
                    mSwipeBackHelper.forward(FileImportWechatActivity.class, Constants.REQ_OPEN_WECHAT);
                }else{
                    ToastUtils.showShort("请给用户授权");
                }
            }
        }

    }

    private void chooseImage() {
        List<String> list = new ArrayList<>();
        list.add("拍照");
        list.add("相册");
        BottomPopupWindow window = new BottomPopupWindow(FileImportActivity.this) {
            @Override
            public void onItemChooseFunction(int position, String s) {
                super.onItemChooseFunction(position, s);
                doOpenTakePhoto(position == 0);
            }

            @Override
            public void onCancel() {
                super.onCancel();
            }
        };
        window.showDialog(list);
    }

    private DialogLoading mDialogLoading;

    private void doOpenTakePhoto(boolean isCamera) {
        final CropOptions options = new CropOptions.Builder()
                .setWithOwnCrop(false)
                .create();
        File cropFile = getPicName();

        TakePhotoManager manager = UTakePhoto.with(FileImportActivity.this)
                .setCrop(options)
                .setCompressConfig(new CompressConfig.Builder().setTargetUri(Uri.fromFile(cropFile)).setLeastCompressSize(50).create());
        if(isCamera) {
            manager.openCamera();
        } else {
            manager.openAlbum();
        }
        manager.build(new ITakePhotoResult() {
            @Override
            public void takeSuccess(List<Uri> uriList) {
                if (uriList.get(0) != null) {
                    try {
                        ParcelFileDescriptor pfd = getActivity().getContentResolver().openFileDescriptor(uriList.get(0), "r");
                        if (pfd != null) {
                            BitmapFactory.decodeFileDescriptor(pfd.getFileDescriptor());
                            String path = cropFile.getPath();

                            if(mDialogLoading == null) mDialogLoading = new DialogLoading(FileImportActivity.this);
                            mDialogLoading.show("照片识别中...");
                            new OCRAPI().getPhoneByPic(path, wordList -> {
                                // todo 上传识别结果
                                if(wordList == null || wordList.size() == 0) {
                                    mDialogLoading.dismiss();
                                    ToastUtils.showShort("未识别到手机号码");
                                    return;
                                }

                                List<SaveCallTaskRequest.Data> taskData = new ArrayList<>();
                                for (int i = 0; i < wordList.size(); i++) {
                                    SaveCallTaskRequest.Data data = new SaveCallTaskRequest.Data();
                                    data.setPhone(wordList.get(i).getWords());
                                    taskData.add(data);
                                }

                                SaveCallTaskRequest bean = new SaveCallTaskRequest();
                                bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
                                bean.setImportGroup(CallGroupEnum.IMPORT_PICTURE);
                                bean.setPersonnelInfoSaveReqVOs(taskData);

                                RequestBody body = getRequestBody(bean);
                                api.doSaveCallTaskToGroup(body).enqueue(new Callback<SaveCallTaskResponse>() {
                                    @Override
                                    public void onResponse(Call<SaveCallTaskResponse> call, Response<SaveCallTaskResponse> response) {
                                        mDialogLoading.dismiss();
                                        if (response.body() != null) {
                                            if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                                ToastUtils.showShort("导入成功");

                                                Intent intent = new Intent();
                                                intent.putExtra(Constants.FILE_IMPORT_TASK_NAME, "");
                                                setResult(RESULT_OK, intent);
                                                mSwipeBackHelper.backward();
                                            } else {
                                                ToastUtils.showShort(response.body().getMsg());
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(Call<SaveCallTaskResponse> call, Throwable t) {
                                        mDialogLoading.dismiss();
                                        ToastUtils.showShort(FileImportActivity.this.getResources().getString(R.string.call_api_error));
                                    }
                                });
                            });
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void takeFailure(TakeException ex) {

            }

            @Override
            public void takeCancel() {

            }
        });
    }

    @NotNull
    private File getPicName() {
        String dateTime = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        return new File(getFilesDir(), "VisualPhone/Photo/compress/" + dateTime + ".jpg");
    }

    @NotNull
    private String getPath() {
        return new File(getFilesDir(), "VisualPhone/Photo/compress/").getPath();
    }

}
